package com.lucky.demo.controller;

import com.github.pagehelper.PageHelper;
import com.lucky.common.pojo.po.UserPO;
import com.lucky.common.service.UserService;
import com.lucky.demo.pojo.dto.DemoDTO;
import com.lucky.common.base.BaseController;
import com.lucky.common.base.ResultVO;
import com.lucky.common.interceptor.Token;
import com.lucky.common.interceptor.TokenType;
import com.lucky.common.pojo.po.OrgPO;
import com.lucky.common.service.OrgService;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.List;

@Controller
@RequestMapping("/demo")
public class DemoThymeleafController extends BaseController {


	@Resource
	OrgService orgService;
    @Autowired
    private UserService userService;

	@Token(TokenType.refresh)
	@RequestMapping("/save")
	public String save(@ModelAttribute("dto") @Valid DemoDTO dto, BindingResult result, ModelMap model) {
		if(result.hasErrors()) {
			for(ObjectError error : result.getAllErrors ()) {
				System.out.println(error.getDefaultMessage () ) ;
			}
			return "demo/add";
		}
		
		return "demo/list";
	}

	@Token
	@RequestMapping("/add")
	public String add(@ModelAttribute("dto") DemoDTO dto) {
		return "demo/add";
	}


	/**
	 * json测试
	 * @param model
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/list")
	public List<UserPO> list(ModelMap model) {

		PageHelper.startPage(1, 10);
		List<UserPO> voList = userService.list();
		model.put("voList", voList);

		return voList;
	}

	/**
	 * forward 測試
	 * @return
	 */
	@RequestMapping("/test2")
	public String test2() {
		return "forward:test";
	}



	@ResponseBody
	@RequestMapping("/success")
	public ResultVO<String> success(ModelMap model) {
		return ResultVO.success("abcdefg");
	}

	@ResponseBody
	@RequestMapping("/fail")
	public ResultVO<String> fail(ModelMap model) {
		return ResultVO.fail("abcdefg");
	}
}
